// index.js
import * as echarts from '../../ec-canvas/ec-canvas';
const defaultAvatarUrl = '/static/images/profile.jpg'
import { historylist , list } from "../../api/iot/persondata"
import store from "../../store/index.js"
import { formatISOTime } from "../../utils/util.js"
import { getInfo } from "../../api/login.js"


Page({
  data: {
    hasUserInfo: false,
    deviceData: {
      nickName: '设备名称',
      dictName: '产品名称',
      action: 0, // 0: 静止, 1: 小幅运动, 2: 大幅运动
      existence: 0, // 0: 无人, 1: 有人
      collectTime: '',
      status: 0, // 0: 离线, 1: 在线
      offlineTime: '',
      historyExistences: [],
      showHistory: false
    },
    ec: {
        onInit: null // 将在 getHistoryExistencesData 后动态设置
    },
    loading: true,
    error: false,
    refreshInterval: null, // 定时器引用
    isRefreshing: false // 手动刷新状态
  },
  
  onLoad() {
    // 检查是否已经登录
    const token = store.getToken()
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }
    // 验证token有效性
    getInfo().then(res => {
      if (res.code !== 200) {
        // token无效，跳转到登录页
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return
      }
      this.setData({
        loading: true,
        error: false
      }, () => {
        // 确保状态更新后再加载数据
        this.getDeviceData()
        this.getHistoryExistenceData()
      })
    //   this.startRefreshTimer()
    }).catch(error => {
      // 请求失败，跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login'
      })
    })
  },
  
  // 开始定时刷新
  startRefreshTimer() {
    // 清除已存在的定时器
    if (this.data.refreshInterval) {
      clearInterval(this.data.refreshInterval)
    }
    const interval = setInterval(() => {
      this.getDeviceData(true) 
    }, 3000) 
    
    // 保存定时器引用
    this.setData({
      refreshInterval: interval
    })
  },
  
  // 停止定时刷新
  stopRefreshTimer() {
    if (this.data.refreshInterval) {
      clearInterval(this.data.refreshInterval)
      this.setData({
        refreshInterval: null
      })
    }
  },
  
  // 手动刷新数据
  onRefreshTap() {
    // 设置刷新状态
    this.setData({
      isRefreshing: true
    })
    
    // 执行刷新
    this.getDeviceData(false).then(() => {
      // 刷新完成后重置状态
      this.setData({
        isRefreshing: false
      })
      
      // 显示刷新成功提示
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 300
      })
    }).catch(() => {
      // 刷新失败也重置状态
      this.setData({
        isRefreshing: false
      })
    })
  },
  
  // 获取设备数据（从设备列表中获取最新数据）
  getDeviceData(isAutoRefresh = false) {
    if (!isAutoRefresh) {
      this.setData({
        loading: true,
        error: false
      })
    }
    // 返回Promise
    return new Promise((resolve, reject) => {
      // 获取设备列表，按收集时间倒序排列，取最新的数据
      list().then(response => {
        if (response.code === 200) {
          if (response.data && response.data.length > 0) {
            const latestDevice = response.data[0];
            // 格式化数据，确保所有字段都有正确的值
            const formattedData = {
              nickName: latestDevice.nickName || '未知设备',
              dictName: latestDevice.dictName || latestDevice.productName || latestDevice.productId || '未知产品',
              action: latestDevice.action !== undefined ? parseInt(latestDevice.action) : 0,
              existence: latestDevice.existence !== undefined ? parseInt(latestDevice.existence) : 0,
              collectTime: latestDevice.collectTime ? formatISOTime(latestDevice.collectTime) : '',
              status: latestDevice.status !== undefined && latestDevice.status !== null ? parseInt(latestDevice.status) : 0,
              offlineTime: latestDevice.offlineTime ? formatISOTime(latestDevice.offlineTime) : '',
              dataId: latestDevice.dataId || latestDevice.id || 0
            };
            
            this.setData({
              deviceData: formattedData,
              loading: false
            })
            
            resolve()
          } else {
            this.setData({
              deviceData: {
                nickName: '暂无设备',
                dictName: '请先绑定设备',
                action: 0,
                existence: 0,
                collectTime: '',
                status: 0,
                offlineTime: '', 
                dataId: 0
              },
              loading: false
            })
            wx.showToast({
              title: '暂无设备数据',
              icon: 'none'
            })
            this.getHistoryActionData();
            resolve()
          }
        } else {
          this.setData({
            loading: false,
            error: true
          })
          wx.showToast({
            title: response.msg || '数据加载失败',
            icon: 'none'
          })
          reject(new Error(response.msg || '数据加载失败'))
        }
      }).catch(error => {
        this.setData({
          loading: false,
          error: true
        })
        wx.showToast({
          title: '网络错误:' + (error.errMsg || error.message || '未知错误'),
          icon: 'none'
        })
        reject(error)
      })
    })
  },
// 切换历史记录面板展开/收起
toggleHistory() {
    this.setData({
      showHistory: !this.data.showHistory
    });
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getDeviceData().then(() => {
      wx.stopPullDownRefresh()
    }).catch(() => {
      wx.stopPullDownRefresh()
    })
  },
  
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  
  onInputChange(e) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  
  onShow(){
    // 页面显示时也验证登录状态
    const token = store.getToken()
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }
    
    // 验证token有效性
    getInfo().then(res => {
      if (res.code !== 200) {
        // token无效，跳转到登录页
        wx.redirectTo({
          url: '/pages/login/login'
        })
        return
      }
      // token有效，刷新设备数据
      // 重置加载状态
      this.setData({
        loading: true,
        error: false
      }, () => {
        this.getDeviceData()
      })
      this.startRefreshTimer()
    }).catch(error => {
      // 请求失败，跳转到登录页
      wx.redirectTo({
        url: '/pages/login/login'
      })
    })
  },
  // 修改方法名，避免歧义
getHistoryExistenceData() {
    const now = new Date();
    const deadlineTime = now.toISOString();
  
    historylist({ deadlineTime }).then(response => {
      if (response.code === 200 && Array.isArray(response.data)) {
        const formatted = response.data.map(item => ({
          ...item,
          collectTime: item.collectTime ? formatISOTime(item.collectTime) : ''
        }));
        this.setData({
          historyExistences: formatted // 使用 historyExistences 存储 existence 数据
        });
        this.initChart(formatted);
      } else {
        this.setData({ historyExistences: [] });
        this.initChart([]);
      }
    }).catch(err => {
      console.error('获取历史 existence 数据失败:', err);
      this.setData({ historyExistences: [] });
      this.initChart([]);
      wx.showToast({ title: '历史数据加载失败', icon: 'none' });
    });
  },
  initChart(data) {
    // 按时间排序（从早到晚）
    const sorted = [...data].sort((a, b) => 
      new Date(a.collectTime) - new Date(b.collectTime)
    );
  
    // 提取时间点（X轴）
    const times = sorted.map(item => {
      const d = new Date(item.collectTime);
      return `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;
    });
  
    // ✅ 提取 existence 值（Y轴）：0=无人, 1=有人
    const existences = sorted.map(item => item.existence);
  
    // 配置 ECharts
    this.setData({
      ec: {
        onInit: (canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          canvas.setChart(chart);
  
          const option = {
            tooltip: {
              trigger: 'axis',
              formatter: (params) => {
                const existence = params[0].value;
                const status = existence === 0 ? '无人' : '有人';
                return `${params[0].name}: ${status}`;
              }
            },
            xAxis: {
              type: 'category',
              data: times,
              boundaryGap: false,
            },
            yAxis: {
              type: 'value',
              min: 0,
              max: 1,
              axisLabel: {
                formatter: function (value) {
                  return value === 0 ? '无人' : '有人';
                }
              }
            },
            series: [{
              name: '人存状态',
              type: 'line',
              data: existences,
              markPoint: {
                data: [
                  {type: 'max', name: '最大值'},
                  {type: 'min', name: '最小值'}
                ]
              },
              markLine: {
                data: [
                  {type: 'average', name: '平均值'}
                ]
              }
            }]
          };
  
          chart.setOption(option);
          return chart;
        }
      }
    });
  },
  
  onHide() {
    // 页面隐藏时停止定时刷新，节省资源
    this.stopRefreshTimer()
  },
  
  onUnload() {
    // 页面卸载时停止定时刷新
    this.stopRefreshTimer()
  }
})